package com.firefoxking.mysite.controller.admin;

import com.firefoxking.mysite.constant.LogActions;
import com.firefoxking.mysite.constant.WebConst;
import com.firefoxking.mysite.controller.BaseController;
import com.firefoxking.mysite.entity.User;
import com.firefoxking.mysite.service.log.LogService;
import com.firefoxking.mysite.service.user.UserService;
import com.firefoxking.mysite.utils.APIResponse;
import com.firefoxking.mysite.utils.Commons;
import com.firefoxking.mysite.utils.IPKit;
import com.firefoxking.mysite.utils.TaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping(value = "/admin")
public class LoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private Commons commons;

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @GetMapping(value = "/login")
    public String getLoginPage(Model model) {
        model.addAttribute("commons", commons);
        return "admin/login";
    }

    // TODO: 登录功能session
    @PostMapping(value = "/login")
    @ResponseBody
    public APIResponse login(Model model,
                             HttpServletRequest request,
                             HttpServletResponse response,
                             @RequestParam(name = "username", required = true)
                             String username,
                             @RequestParam(name = "password", required = true)
                             String password,
                             @RequestParam(name = "remeber_me", required = false, defaultValue = "true")
                             boolean rememberme) {
        String ip= IPKit.getIpAddrByRequest(request); // 获取ip并过滤登录时缓存的bug
        Integer error_count = cache.hget("login_error_count",ip);
        try {
            User user = userService.login(username, password);
            TaleUtils.setCookie(response, user.getUid(), rememberme);
            logService.addLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getUid());
        } catch (Exception e) {
            logger.error(e.getMessage());
            error_count = null == error_count ? 1 : error_count + 1;
            if (error_count > 3) {
                return APIResponse.fail("您输入密码已经错误超过3次，请10分钟后尝试");
            }
            cache.hset("login_error_count", ip,error_count, 10 * 60); // 加入ip的过滤
            String msg = "登录失败";
//            if (e instanceof BusinessException) {
//                msg = e.getMessage();
//            } else {
//                logger.error(msg, e);
//            }
            return APIResponse.fail(msg);
        }
        return APIResponse.success();
    }


    @GetMapping(value = "/logout")
    public String logout(HttpServletResponse response) {
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setValue(null);
        cookie.setMaxAge(0);// 立即销毁cookie
        cookie.setPath("/");
        response.addCookie(cookie);
        return "admin/login";
    }

}
